//定义全局ID ARR
var userid = null;
var useridArr = null;
//插入or修改标志:0,新增 1,修改
var upsert = 0;

var userDatagrid = null;

var roleIdArr = new Array();

$(function() {
	//初始化多选下拉列表
	$("#roleSel").multiselect({
		selectedList: 2, // 0-based index
		header: false
	});
	initDialog();
	initMsgDatagird();
	$("#addUserA").bind("click", function(){
		upsert = 0;
		MZ.clearForm("userForm");
		$("#username").attr("disabled",false); 
		$("#ui-dialog-title-userDialog").text("新增用户");
		MZ.openDialog("userDialog");
	});
	
	$("#updateUserA").bind("click", function(){
		upsert = 1;
		userid = null;
		roleIdArr = new Array();
		MZ.clearForm("userForm");
		var rowVals = userDatagrid.getRowValues();
		//reset
		if(rowVals.length == 1){
			rowVal = rowVals[0];
			if(rowVal.status=="失效"){
				MZ.showMsg("该用户已经失效!");
				return false;
			}
			userid = rowVal.id;
			roleNames = rowVal.roleNames;
			roleNames = roleNames.split(",")
			
			$("#roleSel").multiselect("uncheckAll");
			$(roleNames).each(function(){
//				$("#roleSel").multiselect("widget").find(":checkbox[title="+this+"]").each(function(){
//					 this.click();
//				});
				$("#roleSel").multiselect("widget").find(":checkbox[title="+this+"]").click();
				roleIdArr.push($("#roleSel").multiselect("widget").find(":checkbox[title="+this+"]").val());
			});
			loadUser(rowVal);
			$("#ui-dialog-title-userDialog").text("修改用户");
			MZ.openDialog("userDialog");
		}else{
			MZ.showMsg("请选择一行记录修改!");
		}
	});
	
	$("#delUserA").bind("click", function(){
		useridArr = null;
		useridArr = userDatagrid.getRowValue(2);
		if(useridArr.length >= 1){
			var status = userDatagrid.getRowValue(5);
			if(jQuery.inArray("失效", status) != -1){
				MZ.showMsg("已失效的用户不需要再删除!");
				return false;
			}
			MZ.openDialog("dialog-confirm");
		}else{
			MZ.showMsg("请选择一行记录修改!");
		}
	});
	
	$("#submitBtn").bind("click", function(){
		if(upsert == 0){
			addUser();
		}else if(upsert == 1){
			updateUser();
		}
	});
	$("#resetBtn").bind("click", function(){
		MZ.clearForm("userForm");
	});
	
	$("#searchA").bind("click", function(){
		searchUser();
	});
	
	$("#resetA").bind("click", function(){
		$("#nicknameText").val("");
	});
	
	
});

function initDialog(){
	//DIALOG//
	$('#userDialog').dialog({
		autoOpen: false,
		width: 500,
		height: 450,
		modal: true
	});
	
	$( "#dialog-confirm" ).dialog({
		resizable: false,
		autoOpen: false,
		height:180,
		modal: true,
		buttons: {
			"确认删除": function() {
				delUser();
				$( this ).dialog( "close" );
			},
			"取消": function() {
				$( this ).dialog( "close" );
			}
		}
	});
}

//init message datagird
//get json data from server
function initMsgDatagird(){
	//var width = $("#searchBox").width()-0;
	userDatagrid = $("#msgDatagird").flexigrid({
		url: "usermanager/getUserInfo",
		colModel : [
		    {display: "ID", name : "id", width : 90, sortable : true, hide: true},
			{display: "用户", name : "username", width : 150, sortable : true},
			{display: "姓名", name : "nickname", width : 150, sortable : true, hide: false},
			{display: "状态", name : "status", width : 90, sortable : true, process:formatStatus},
			{display: "部门", name : "deptName", width : 120, sortable : true},
			{display: "DID", name : "deptId", width : 90, sortable : true, hide: true},
			{display: "角色", name : "roleNames", width : 150, sortable : true},
			{display: "电话", name : "phone", width : 120, sortable : true},
			{display: "电话", name : "email", width : 120, sortable : true},
			{display: "备注", name : "description", width : 240, sortable : true}
		],
		onSelectRow: false
    });
}

//funciton onSelectRow required
//update flexigrid onselectrow function
//if you need't use onselect row
//let this function blank to do nothing
function onSelectRow(tr){
	var trId = tr.id;
	var msgid = $("#"+trId+" td[abbr='username']").text();
	alert(msgid);
}

//格式化用户STATUS显示
function formatStatus(tdDiv, pid){
	var status = $(tdDiv).text();
	if(status == 1){
		return "<font color='green'>正常</font>";
	}else if(status == 2){
		return "已锁定";
	}else{
		return "<font color='red'>失效</font>";
	}
}

//LOAD USER INFO 2 FORM 4 UPDATE
function loadUser(jsonData){
	//userTable
	$("#username").attr("disabled",true); 
	for(var key in jsonData){
		$("#"+key).val(jsonData[key]);
	}
	$("#deptSel").val(jsonData.deptId);
}

function searchUser(){
	var nickName = $("#nicknameText").val();
	var deptName = $("#deptSearchSel").find("option:selected").text();
	var params = [{name: "nickName", value: nickName},{name: "deptName", value: deptName}];
	$("#msgDatagird").flexOptions({newp: 1, params: params}).flexReload();
}

function addUser(){
	var params = $('#userForm').serializeObject();
	var deptName = $("#deptSel").find("option:selected").text();
	var deptId = $("#deptSel").val();
//	var roleName = $("#roleSel").find("option:selected").text();
	var roleIds = $("#roleSel").val();
	params["deptName"]=deptName;
	params["deptId"]=deptId;
	if(roleIds != null){
		params["roleIds"]=roleIds;
	}
	if(!validUserForm(params)) {
		return false;
	}
	params = $.toJSON(params);
	$.ajax({
		url : "usermanager/addUserInfo",
//		processData: false,
		type : "post",
		data : "data="+params,
//		dataType : "json",
//		contentType : "application/json",
		beforeSend : function() {
//			MZ.clearForm("userForm");
		},
		success : function(result) {
			if(result.succeed){
				MZ.reloadDatagrid("msgDatagird");
			}else{
				MZ.showMsg(result.message);
			}
			MZ.closeDialog("userDialog");
		},
		error: function(result){
			MZ.showMsg(result);
		}
	});
}

function updateUser(){
	var params = $('#userForm').serializeObject();
	var deptName = $("#deptSel").find("option:selected").text();
	var deptId = $("#deptSel").val();
//	var roleName = $("#roleSel").find("option:selected").text();
//	var roleIds = $("#roleSel").val();
	var roleIds = $("#roleSel").multiselect("getChecked").map(function(){
	   return this.value;	
	}).get();
	if(roleIds != null){
		params["roleIds"]=roleIds;
	}else{
		params["roleIds"]=roleIdArr;
	}
	params["id"]=userid;
	params["deptName"]=deptName;
	params["deptId"]=deptId;
	if(!validUserForm(params)) {
		return false;
	}
	params = $.toJSON(params);
	$.ajax({
		url : "usermanager/updateUserInfo",
		// processData: false,
		type : "post",
		data : "data="+params,
		beforeSend : function() {
		},
		success : function(result) {
			if(result.succeed){
				MZ.reloadDatagrid("msgDatagird");
			}else{
				MZ.showMsg(result.message);
			}
			MZ.closeDialog("userDialog");
		},
		error: function(result){
			MZ.showMsg(result);
		}
	});
}

function delUser(){
	var params = {"ids":useridArr.toString()};
	$.ajax({
		url : "usermanager/delUserInfo",
		// processData: false,
		type : "post",
		data : params,
		beforeSend : function() {
		},
		success : function(result) {
			if(result.succeed){
				MZ.reloadDatagrid("msgDatagird");
			}else{
				MZ.showMsg(result.message);
			}
		},
		error: function(result){
			MZ.showMsg(result);
		}
	});
}

//FOR AJAX validate
function validUserForm(formParams){
	//insert
	//valid username
	if(upsert == 0){
		username = formParams["username"];
		if($.trim(username)==""){
			MZ.showMsg("用户名不能为空!");
			return false;
		}else{
			if(!checkUn(formParams["username"])){
				MZ.showMsg("用户名已存在!");
				return false;
			}
		}
	}
	//valid nickname
	if($.trim(formParams["nickname"])==""){
		MZ.showMsg("用户名姓名不能为空!");
		return false;
	}
	//valid password
	var password = formParams["password"];
	password = $.trim(password);
	if(upsert == 0){
		if(!checkPw(password, formParams["passwordConfirm"])){
			return false;
		}
	}else{
		if(password != ""){
			if(!checkPw(password, formParams["passwordConfirm"])){
				return false;
			}
		}
	}
	//valid deptName
	if($.trim(formParams["deptName"])==""){
		MZ.showMsg("请选择一个部门!");
		return false;
	}
	//valid roleName
//	if($.trim(formParams["roleIds"])==""){
//		MZ.showMsg("请选择至少一个系统角色!");
//		return false;
//	}
	//valid phone
	var reg = null;
	if($.trim(formParams["phone"])!=""){
		reg=/^[0-9\-\+\(\)]*$/;
		if(!reg.test(formParams["phone"])){
			MZ.showMsg("请输入正确的联系号码!");
			return false;
		}
	}
	//valid email
	if($.trim(formParams["email"])!=""){
		reg=/^[a-zA-Z0-9]([a-zA-Z0-9]*[-_.]?[a-zA-Z0-9]+)+@([\w-]+\.)+[a-zA-Z]{2,}$/;
		if(!reg.test(formParams["email"])){
			MZ.showMsg("请输入正确的邮箱地址!");
			return false;
		}
	}
	return true;
}

function checkUn(username){
	var flag = false;
	$.ajax({
		url: "usermanager/checkUn", 
	    //processData: false,
		type: "post",
		async: false,
		data: {"username":username},
		success: function(result){
			flag = result;
		},
		error: function(result){
			MZ.showMsg(result);
		}
	});
	return flag;
}
function checkPw(password, passwordConfirm){
	if(password==""){
		MZ.showMsg("密码不能为空!");
		return false;
	}else if(password.length<6){
		MZ.showMsg("密码过短(6-16长度)!");
		return false;
	}else if(password!=$.trim(passwordConfirm)){
		MZ.showMsg("两次密码不一致!");
		return false;
	}
	return true;
}


